package com.atguigu.gmall.cart.service.impl;

import com.atguigu.gmall.cart.mapper.CartInfoMapper;
import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.cart.util.CartThreadLocalUtil;
import com.atguigu.gmall.common.constant.CartInfoConst;
import com.atguigu.gmall.model.base.BaseEntity;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.ProductFeign;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.util.concurrent.AtomicDouble;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 购物车相关接口实现类
 */
@Service
public class CartInfoServiceImpl implements CartInfoService {

    @Autowired
    private ProductFeign productFeign;
    @Resource
    private CartInfoMapper cartInfoMapper;
    /**
     * 购物车新增
     * @param skuId
     * @param num
     */
    @Override
    public void addCart(Long skuId, Integer num) {
        //参数校验
        if (skuId == null || num == null) {
            throw new RuntimeException("参数异常");
        }
        //查询商品是否存在 //调用product微服务的方法
        SkuInfo skuInfo = productFeign.getSkuInfo(skuId);
        if (skuInfo == null || skuInfo.getId() == null) {
            throw new RuntimeException("商品不存在");
        }
        String s = CartThreadLocalUtil.get();
        System.out.println(s);
        //查询购车中是否已经存在数据
       CartInfo cartInfo = cartInfoMapper.selectOne(new LambdaQueryWrapper<CartInfo>()
                .eq(CartInfo::getUserId, CartThreadLocalUtil.get()).eq(CartInfo::getSkuId, skuId));

        if (cartInfo == null ) {
            if (num <= 0){
                return;
            }else {
                //购物车中没有 新增
                //初始化
                cartInfo = new CartInfo();
                cartInfo.setUserId(CartThreadLocalUtil.get());
                cartInfo.setSkuId(skuId);
                cartInfo.setSkuName(skuInfo.getSkuName());
                cartInfo.setSkuNum(num);
                cartInfo.setImgUrl(skuInfo.getSkuDefaultImg());
                //查询实时价格
                BigDecimal price = productFeign.getPrice(skuId);
                if (price == null) {
                    throw new RuntimeException("商品价格异常");
                }
                cartInfo.setCartPrice(price);
                int insert = cartInfoMapper.insert(cartInfo);
                if (insert <= 0) {
                    throw new RuntimeException("添加购物失败");
                }
            }
        } else {
            //如果已经存在进行修改
            //判断商品数量
             num = cartInfo.getSkuNum() + num;
            if (num <= 0) {
                int delete = cartInfoMapper. deleteById(cartInfo.getId());
                if (delete < 0) {
                    throw new RuntimeException("删除失败");
                }
            }
            //数量覆盖
            cartInfo.setSkuNum(num);
            int update = cartInfoMapper.updateById(cartInfo);
            if (update < 0) {
                throw new RuntimeException("修改购物车数据失败");
            }
        }
    }

    /**
     * 查询用户购物车中的数据
     *
     *
     * @return
     */
    @Override
    public List<CartInfo> getCartInfo() {
        return  cartInfoMapper.
                selectList(new LambdaQueryWrapper<CartInfo>().
                        eq(CartInfo::getUserId, CartThreadLocalUtil.get()));
    }

    /**
     * 选中状态修改
     *
     * @param id
     * @param status
     */
    @Override
    public void checkUpdate(Long id,  Short status) {
        int i = 0;
        //选中全部
        if (id == null){
             i = cartInfoMapper.updateCheckAll(status, CartThreadLocalUtil.get());
        }else {
            //选中单个
            i = cartInfoMapper.updateCheck(id,status,CartThreadLocalUtil.get());
        }
        if (i < 0 ){
            throw new RuntimeException("修改上下架失败");
        }
    }

    /**
     * 删除购物车中的数据
     *
     * @param id
     */
    @Override
    public void removeCart(Long id) {
        if (id == null){
            return;
        }
        int delete = cartInfoMapper.delete(new LambdaQueryWrapper<CartInfo>().
                eq(CartInfo::getUserId, CartThreadLocalUtil.get()).eq(BaseEntity::getId, id));
        if (delete < 0 ){
            throw new RuntimeException("删除购物车中数据失败");
        }
    }

    /**
     * 修改购物车中商品数量
     * @param id
     * @param num
     */
    @Override
    public void updateCartNum(Long id,Integer num) {
        if (id == null){
            return;
        }
        if (num <= 0){
            int delete = cartInfoMapper.
                    delete(new LambdaQueryWrapper<CartInfo>().
                            eq(BaseEntity::getId, id).eq(CartInfo::getUserId, CartThreadLocalUtil.get()));
            if (delete < 0 ){
                throw new RuntimeException("删除购物车中数据失败");
            }
        }else {
            int i = cartInfoMapper.updateCartInfoNum(id, num, CartThreadLocalUtil.get());
            if (i < 0){
                throw new RuntimeException("修改购物车中商品数量失败");
            }
        }
    }

    /**
     * 用户·登录后合并购物车
     *
     * @param cartInfoList
     */
    @Override
    public void mergeCart(List<CartInfo> cartInfoList) {
        cartInfoList.stream().forEach(cartInfo -> {
            addCart(cartInfo.getSkuId(),cartInfo.getSkuNum());
        });
    }

    /**
     * 查询用户当前订单中的购物车数据
     * @return
     */
    @Override
    public Map<String, Object> getOrderConfirmCart() {
        //初始化返回对象
        Map<String, Object> result = new HashMap<>();
        List<CartInfo> cartInfoList = cartInfoMapper.selectList(new
                LambdaQueryWrapper<CartInfo>().
                eq(CartInfo::getUserId, CartThreadLocalUtil.get()). //根据当前用户和购物车中已经选择来查询
                eq(CartInfo::getIsChecked, CartInfoConst.CHECK));
        //计算总金额和总数量
        //初始化总数量
        AtomicInteger totalNum = new AtomicInteger(0);
        //初始化总金额
        AtomicDouble totalPrice = new AtomicDouble(0);
        List<CartInfo> cartInfoList1 = cartInfoList.stream().map(cartInfo -> {
            //获取总数量
            totalNum.getAndAdd(cartInfo.getSkuNum());
            //获取总金额
            //先获取当前的实时价格 购物车不能直接调用因此要使用product微服务
            BigDecimal price = productFeign.getPrice(cartInfo.getSkuId());
            totalPrice.getAndAdd(price.doubleValue() * cartInfo.getSkuNum());
            //将实时价格保存
            cartInfo.setSkuPrice(price);
            //返回cartInfo 反回实时价格
            return cartInfo;
        }).collect(Collectors.toList());
        if (!StringUtils.isEmpty(totalNum) &&
                !StringUtils.isEmpty(totalPrice) &&
                !cartInfoList1.isEmpty()) {
            result.put("totalNum", totalNum);
            result.put("totalPrice", totalPrice);
            result.put("cartInfoList", cartInfoList1);
            return result;
        }else {
            return null;
        }
    }

    /**
     * 根据用户名删除购物车中数据
     */
    @Override
    public void clearCart() {
        int delete = cartInfoMapper.
                delete(new LambdaQueryWrapper<CartInfo>().
                        eq(CartInfo::getUserId, CartThreadLocalUtil.get())
                        .eq(CartInfo::getIsChecked,CartInfoConst.CHECK));
        if (delete < 0){
            throw new RuntimeException("清空购物车数据失败");
        }
    }
}
